﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SceneActDrop : MonoBehaviour
{
    public float actDropDonwInSeconds = 2f;
    private float width;
    private bool running;
    private float speed;
    private float runTime;

    private string sceneName;
    private static SceneActDrop instance;

    private UnityEngine.Events.UnityAction endCallback;

    public static SceneActDrop Instance()
    {
        return instance;
    }
    public string getSceneName()
    {
        return sceneName;
    }
    private void Awake()
    {
        instance = this;
        this.sceneName = gameObject.scene.name;

        if (transform.TryGetComponent(out RectTransform rTransform))
        {
            if (transform.parent.TryGetComponent(out RectTransform prTransform))
            {
                Vector3[] corners = new Vector3[4];
                prTransform.GetLocalCorners(corners);
                //prTransform.GetWorldCorners(aa);
                Vector3 min = corners[0];
                Vector3 max = corners[2];
                Vector3 rect = max - min;
                float width = rect.x;
                float height = rect.y;
                this.width = width;
                this.speed = this.width / actDropDonwInSeconds;
                rTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
                rTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            }
            rTransform.pivot = new Vector2(1f, 0.5f);
            rTransform.anchorMin = new Vector2(1f, 0.5f);
            rTransform.anchorMax = new Vector2(1f, 0.5f);
            rTransform.anchoredPosition=Vector2.zero;
            if (transform.TryGetComponent(out Image image))
            {
                image.color = Color.black;
            }
        }
        else
        {
            gameObject.SetActive(false);
        }
        Stop();
    }
    void Start()
    {
    }
    private void FixedUpdate()
    {
        UpdateActDrop();
    }

    public void Run(UnityEngine.Events.UnityAction endCallback)
    {
        if (!running)
        {
            this.endCallback = endCallback;
            runTime = Time.time;
            running = true;
        }
    }
    public void Stop()
    {
        if (running)
        {
            running = false;
            if (this.endCallback != null)
            {
                this.endCallback.Invoke();
            }
        }
    }
    private void UpdateActDrop()
    {
        if (running)
        {
            width -= speed * Time.deltaTime;
            if (transform.TryGetComponent(out RectTransform rTransform))
            {
                rTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
            }
            if (width <= 0)
            {
                Stop();
                gameObject.SetActive(false);
            }
        }
    }
}
